package cn.jolyoulu.common.web.security.utils;

import cn.jolyoulu.common.web.security.constant.SecurityConstants;
import cn.jolyoulu.common.web.security.constant.TokenConstants;
import cn.jolyoulu.common.web.security.context.SecurityContextHolder;
import cn.jolyoulu.common.web.security.entity.LoginUser;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Objects;

/**
 * @Author LuZhouJin
 * @Date 2023/3/17
 * 权限获取工具类
 */
public class SecurityUtils {
    /**
     * 获取用户ID
     */
    public static String getUserId() {
        if (getLoginUser() ==null){
            return null;
        }
        return getLoginUser().getUserId();
    }

    /**
     * 获取登录用户信息
     */
    public static LoginUser<?> getLoginUser() {
        return SecurityContextHolder.get(SecurityConstants.LOGIN_USER, LoginUser.class);
    }

    /**
     * 根据request获取请求token
     */
    public static String getToken(HttpServletRequest request) {
        String bearerToken = request.getHeader(TokenConstants.AUTHENTICATION);
        if (Objects.isNull(bearerToken)) {
            return "";
        }

        if (bearerToken.startsWith(TokenConstants.PREFIX)) {
            //截取token
            return bearerToken.substring(TokenConstants.PREFIX.length());
        }

        return bearerToken;
    }
}
